$(function () {

    var lotterySucess = false
    var eggindex = 0;
    var dealerNo = getQueryString("dealerNo");
    var activityCode = getQueryString("activityCode");
    var param = {
        dealerNo: dealerNo,
        activityCode: activityCode
    };

    var urlSplit = window.location.href.split("/");

    var common = {
        prize: {},
        urlPage: 'http://127.0.0.1:5500/static',
        // url: 'http://192.168.14.187:8090',
        url: window.location.protocol + "//" + window.location.host + "/" + urlSplit[3] + "/" + urlSplit[4],
        // url: 'http://192.168.14.184:8080/activity',
        notice1: "目前参与人数较多，请稍后再试！",
        // skipUrl: "https://live.polyv.cn/watch/239952",
        deploycolId: "",
    };

    LotteryVo.common = common
        
    $.ajax({
        type: 'get',
        url: common.url + "/external/getServerConfig",
        dataType: "json",
        success: function (data) {
    
            if (!data.success) {
                return;
            }
    
            var resp = JSON.parse(data.content.serverConfig);
    
            var tempKeys = [];
    
            for (var i = 0; i < resp.groupList.length; i++) {
                tempKeys.push(resp.groupList[i]["group_id"]);
            }
            
            for (var j = 0; j < tempKeys.length; j++) {
                var temp = resp[tempKeys[j]];
                var tempData = {};
                var tempCode = "";
                for (var k = 0; k < temp.length; k++) {
                    if (temp[k]["type"] == "picture") {
                        tempData["url"] = temp[k]["url"];
                        tempData["position"] = temp[k]["key"];
                    }
                    if (temp[k]["key"] == "awardsName") {
                        tempData["title"] = temp[k]["value"];
                    }
                    if (temp[k]["key"] == "prizeType") {
                        tempData["status"] = temp[k]["value"];
                    }
                    if (temp[k]["key"] == "awardsCode") {
                        tempData["awardsCode"] = temp[k]["value"];
                        tempCode = temp[k]["value"];
                    }
                    if (temp[k]["key"] == "skipUrl") {
                        common["skipUrl"] = temp[k]["value"];
                    }
                }
            
                common.prize[tempCode] = tempData;
            
                // $("#" + tempData["position"]).attr("src", tempData["url"]);

                if ($("." + tempData["position"])[0] && $("." + tempData["position"])[0].tagName === "IMG" && !!tempData["url"]) {
                    $("." + tempData["position"]).attr("src", tempData["url"]);
                } else if ($("." + tempData["position"])[0] && $("." + tempData["position"])[0].tagName !== "IMG" && !!tempData["url"]){
                    $("." + tempData["position"]).css("background","url(" + tempData["url"] + ")");
                    $("." + tempData["position"]).css("backgroundSize","cover");
                }

            }

            common["deploycolId"] = data.content.deploycolId;
    
            LotteryVo.common = common
            
        },
    });

    $('.btn').click(function () {
        var isLogin = localStorage.getItem("isLogin") ? JSON.parse(localStorage.getItem("isLogin")) : {
            login: 0,
            staffNum: ""
        };
        if (isLogin && isLogin.login == 1) {

            $.ajax({
                url: common.url + "/auldraw/winner/record?dealerNo=" + JSON.parse(localStorage
                    .getItem("isLogin")).staffNum,
                type: 'GET',
                dataType: "json",
                success: function (data) {

                    if (data && data.content) {

                        if (Object.keys(data.content).length !== 0) {

                            var str = "";

                            var keys = Object.keys(data.content);

                            for (var i = 0; i < keys.length; i++) {

                                var realityString = '';

                                if (data.content[keys[i]]["giftCode"] !== "8080" && common.prize[data.content[keys[i]].giftCode].status ==="1") {

                                    if (!data.content[keys[i]]["detailAddress"]) {
                                        realityString =
                                            '<a style="color: inherit;display:inline;margin-left:10px"' +
                                            'data-quali="' + keys[i] + '"' +
                                            'class="addressModal" href="javascript:void(0);' +
                                            '">' + '点此填写收货地址</a>'
                                    } else {
                                        realityString =
                                            '<a class="addressDetailModal" style="color: inherit;margin-left:10px;display:inline"' + 'data-name="' + data.content[keys[i]]["receiverName"] + '"' + 'data-phone="' + data.content[keys[i]]["receiverPhone"] + '"' + 'data-city="' + data.content[keys[i]]["cityCode"] + '"' + 'data-province="' + data.content[keys[i]]["provinceCode"] + '"' + 'data-town="' + data.content[keys[i]]["townCode"] + '"' + 'data-address="' + data.content[keys[i]]["detailAddress"] + '"' + ' href="javascript:void(0);'  + '">' + '查看地址</a>'
                                    }

                                }

                                var paddingString = "";

                                if (data.content[keys[i]]["giftCode"] === "8080") {
                                    paddingString = "未中奖";
                                } else {
                                    paddingString = "恭喜您获得";
                                }

                                str = str + '<p>' + paddingString +'<span class="yellow">' + (common.prize[data.content[keys[i]].giftCode] ? common.prize[data.content[keys[i]].giftCode].title : "") + realityString + '</span></p>';

                            }

                        } else if (Object.keys(data.content).length === 0) {
                            str = '<p class="t-c">暂无中奖记录</p>';
                        } else {
                            str = '<p class="t-c">暂无中奖记录</p>';
                        }

                        LotteryVo.handleOpenLotteryRecord(str)    

                        // layer.open({
                        //     title: '中奖记录',
                        //     className: 'drawNotice',
                        //     content: str + '<div class="button">确定</div>',
                        //     style: 'width:6.6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;height:8rem;overflow:scroll',
                        //     shadeClose: false,
                        //     end: function () {
                        //     }
                        // });
                        // $(".drawNotice  .button").on("click", function () {
                        //     layer.closeAll();
                        //     getLotteryCount();
                        // })
                        return
                    }
                }
            })


        } else {
            LoginActionVo.openLogin(2)
            // login(2);
        }
    });


    function getCity(data) {
        var a = b = c = '';
        $.each(window.cityData, function (i, province) {
            if (province.code === data.provinceCode) {
                a = province.name + ' ';
                $.each(province.sub, function (i, city) {
                    if (city.code === data.cityCode) {
                        b = city.name + ' ';
                        $.each(city.sub, function (i, town) {
                            if (town.code === data.townCode) {
                                c = town.name + ' ';
                            }
                        })
                    }
                })
            }
        })
        return a + b + c;
    }


    $("#container").on("click", ".addressDetailModal", function() {
        
        var name = $(this).data("name");
        var phone = $(this).data("phone");
        var city = $(this).data("city");
        var province = $(this).data("province");
        var town = $(this).data("town");
        var address = $(this).data("address");

        var str = '<div class=""><div><div class=""><div class="form-item"><label>姓名</label><div><input data-code="receiverName" type="text" id="name"></div></div>' +
                  '<div class="form-item"><label>联系电话</label><div><input data-code="receiverPhone" type="tel" id="tel"></div></div><div class="form-item"><label>地址</label><div class=""><input class="input-pch" data-code="city" type="text" placeholder="请选择城市" id="city"></div></div>' +
                  '<div class="form-item"><label>门牌号</label><div><input data-code="detailAddress" type="text" id="address"></div></div><div class="form-item t-c"></div></div></div></div>'

                  LotteryVo.handleLotteryOfAddress(str)          
        // layer.open({
        //     title: '查看收货地址',
        //     className: 'addressFormDetailForm',
        //     content: str + '<div style="text-align:center">' + '<button class="button" id="cancel" style="height:0.8rem;line-height:0.8rem;width:2rem;display:inline-block">取消</button>' + '</div>',
        //     style: 'width:6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;',
        //     shadeClose: false,

        // });
        // $(".addressFormDetailForm  #cancel").on("click", function () {
        //     layer.closeAll();
        //     getLotteryCount();
        // });

        $('input[data-code="receiverName"]').val(name);
        $('input[data-code="receiverName"]').attr("disabled", "disabled");
        $('input[data-code="receiverPhone"]').val(phone);
        $('input[data-code="receiverPhone"]').attr("disabled", "disabled");
        $('input[data-code="city"]').val(getCity({
            cityCode: city,
            townCode: town,
            provinceCode: province,
        }));
        $('input[data-code="city"]').attr("disabled", "disabled");
        $('input[data-code="detailAddress"]').val(address);
        $('input[data-code="detailAddress"]').attr("disabled", "disabled");
            
               
    });


    $("#container").on("click", ".addressModal", function () {
        
        var qualiSeqNo = $(this).data("quali");
        $(".drawNotice  .button").click();

       var str =  '<div>' + '<div>' + '<div><div class="form-item">' +
            '<label>姓名</label>' + '<div><input data-code="receiverName" type="text" id="name"></div>' + '</div><div class="form-item"><label>联系电话</label><div>' +
            '<input data-code="receiverPhone" type="tel" id="tel"></div></div>' + '<div class="form-item"><label>地址</label><div class="arrow"><input class="input-pch" data-code="city" type="text" placeholder="请选择城市" id="city"></div></div>' +
            '<div class="form-item"><label>门牌号</label><div><input data-code="detailAddress" type="text" id="address"></div></div><div class="form-item t-c"></div></div></div></div>'
        

            LotteryVo.handleLotteryFillAddress(str)

        // layer.open({
        //     title: '填写收货地址',
        //     className: 'addressFormModal',
        //     content: str + '<div style="text-align:center">' + '<button class="button" id="submitAddress" style="height:0.8rem;line-height:0.8rem;width:2rem;display:inline-block;margin-right:10px">提交</button>' + '<button class="button" id="cancel" style="height:0.8rem;line-height:0.8rem;width:2rem;display:inline-block">取消</button>' + '</div>',
        //     style: 'width:6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;',
        //     shadeClose: false,
        //     end: function () {
        //         // if (!(lottery.data.status == 1)) {
        //         //     location.href = common.skipUrl;
        //         // }
        //     }
        // });
        // $(".addressFormModal  #cancel").on("click", function () {
        //     layer.closeAll();
        //     getLotteryCount();
        // });
        // $(".addressFormModal").on("click", "#cancel" ,function () {
        //     layer.closeAll();
        //     getLotteryCount();
        // });


        // 添加地址
        $(".addressFormModal  #submitAddress").on("click", function () {
            var codes = $('#city').attr('data-codes');
        var codeArr = codes ? codes.split(',') : [];
        var reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
        var params = {
            cardNo: JSON.parse(localStorage.getItem('isLogin')).staffNum,
            receiverName: $('#name').val(),
            receiverPhone: $('#tel').val(),
            provinceCode: codeArr[0],
            cityCode: codeArr[1],
            townCode: codeArr[2],
            detailAddress: $('#address').val()
        }
        var msg = "";
        for (var k in params) {
            if (!params[k]) {
                if (k == 'provinceCode' || k == 'cityCode' || k == 'townCode') {
                    msg = $('[data-code="city"]').closest('.form-item').find('label').text() + '不能为空！';
                } else {
                    msg = $('[data-code=' + k + ']').closest('.form-item').find('label').text() + '不能为空！';
                }
                break;
            }
            if (k == 'receiverName' && params[k].length > 10) {
                msg = '姓名长度不能超过10位！';
                break;
            }
            if (k == 'receiverPhone' && !reg.test(params[k])) {
                msg = '联系电话格式不正确！';
                break;
            }
            if (k == 'detailAddress' && params[k].length > 100) {
                msg = '门牌号长度不能超过100！';
                break;
            }
        }
        if (msg) {
            // 提交地址错误提示 
            LotteryVo.handleSubmitAddressErrorTip(msg)
            // layer.open({
            //     type: 3,
            //     title: '温馨提示',
            //     className: 'errortNotice',
            //     content: '<div class="notice">' + msg + '</div><div class="button" id="errorButton">确定</div>',
            //     style: 'width:6rem; background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;',
            //     shadeClose: false,
            // });

            // $(".errortNotice #errorButton").on("click", function () {
            //     layer.close($(".errortNotice #errorButton").closest(".layermbox").attr("index"));
            // })

        } else {
            var t = +new Date();
            $.ajax({
                url: common.url + "/auldraw/address/create",
                type: 'POST',
                data: JSON.stringify({
                    dealerNo: JSON.parse(localStorage.getItem("isLogin")).staffNum,
                    receiverName: $('#name').val(),
                    receiverPhone: $('#tel').val(),
                    provinceCode: codeArr[0],
                    cityCode: codeArr[1],
                    townCode: codeArr[2],
                    detailAddress: $('#address').val(),
                    qualiSeqNo: qualiSeqNo,
                }),
                contentType: 'application/json;charset=UTF-8',
                dataType: 'json',
                beforeSend: function () {
                    loading(1);
                },
                complete: function () {
                    loading();
                },
                success: function (data) {
                    if (data && data.code == 0) {
                        LotteryVo.handleSubmitAddressSuccessTip(data.content)
                        // layer.open({
                        //     title: '&nbsp;',
                        //     className: 'drawNotice',
                        //     content: '<div class="zjnotice t-c">' + data.content +
                        //         '</div><div class="button">' + '关闭' + '</div>',
                        //     style: 'width:6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;',
                        //     shadeClose: false,
                        //     end: function () {
                        //         // location.href = common.skipUrl;
                        //     }
                        // });
                        // $(".drawNotice  .button").on("click", function () {
                        //     layer.closeAll();
                        //     getLotteryCount();
                        // })
                    }
                },
                error: function (err) {

                },
            });
        }


        });

        $(function () {
            var city = cityData;
            
            $("#city").cityPicker({
                title: "请选择收货地址",
                raw: city
            });
        })
    });


    // $('.btn-close').tap(function () {
    //     $('.dialog-result').removeClass('showDialog showEggOpenAnimate').hide();
    // })

    $(".btn-close").on("click",function () {
        $('.dialog-result').removeClass('showDialog showEggOpenAnimate').hide();
    })

    //获取url参数
    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return r[2];
        return null;
    }

    window.canDraw = true;

    $('.egg-box').click(function () {

        var that = $(this)

        if (window.restCount === "0") {
			window.canDraw = true;
		}
        console.log(window.canDraw, '点击金蛋')   
        if (window.canDraw) {
            alertLayer(that);
        }
        
    });

    // function getLotteryCount() {
    //     if (JSON.parse(localStorage.getItem("isLogin")) && JSON.parse(localStorage.getItem("isLogin")).login !== 0) {
    //         $.ajax({
    //             type: 'get',
    //             url: common.url + "/auldraw/quali/count?dealerNo=" + JSON.parse(localStorage.getItem("isLogin")).staffNum,
    //             success: function (data) {
    //                 $("#lotteryTimes").html("您还有" + data.content.count + "次抽奖机会");
    //                 window.restCount = data.content.count
    //             },
    //         });
    //     }
    // }

    LotteryVo.getLotteryCount()
    // window.onload = function() {
    //     getLotteryCount();
    // }


    //登录相关操作
    function alertLayer(eggBox) {

        if (common.deploycolId !== localStorage.getItem("deploycolId")) {
            localStorage.removeItem("isLogin");
        }

        var isLogin = localStorage.getItem("isLogin") ? JSON.parse(localStorage.getItem("isLogin")) : {
            login: 0,
            staffNum: ""
        };
        if (isLogin.login == 0) { //未登陆
            // login(1);
            LoginActionVo.openLogin(1)
        } else {

            if (window.restCount === "0") { // 抽奖次数为 0
                // layer.open({
                //     type: 3,
                //     title: [
                //         '温馨提示',
                //         'background-color:transparent; color: black; text-align:center;'
                //     ],
                //     className: 'startNotice',
                //     content: '<div class="zjnotice">' + '您抽奖已超过指定次数' +
                //     '</div><div class="button">' + (
                //         '<a style="text-decoration: none; color: #ff8800;" href="javascript:void(0);" id="checkHistory">查看中奖记录</a>'
                //     ) + '</div>',
                //     style: 'width:6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;font-size:18px',
                //     shadeClose: false,
                //     end: function () {
                //         // location.href = common.skipUrl;
                //     }
                // });
                // $(".startNotice  .button").on("click", function () {
                //     layer.closeAll();
                //     getLotteryCount();
                // })

                // $(".startNotice #checkHistory").on("click", function () {
                //     $('.btn').click();
                // })
                LotteryVo.handleLotteryNoOfZero()
                return;
            }
            

            // 正式开始抽奖

            window.canDraw = false;

            var that = $(eggBox);
            var dealerNo = JSON.parse(localStorage.getItem("isLogin")).staffNum;
            console.log(lotterySucess,'??阻断请求')
            if (lotterySucess) return;
            $.ajax({
                type: 'get',
                url: common.url + "/lottery/act?dealerNo=" + dealerNo,
                dataType: "json",
                success: function (data) {
                    if (data.success && data.code === 0) {

                        localStorage.setItem("qualiSeqNo", data.content.qualiSeqNo);

                        // if (that.attr('data-egg') == 'left') {
                        //     that.addClass('eggLeftClicked');
                        //     $('.lottery-text').addClass('showEggOpenAnimate');
                        //     $('.egg-broken-wrap').addClass('eggLeft showEggOpenAnimate');
                        //     $('.hammer').addClass('hammer-left');
                        //     $('.light').addClass('light-eggLeft showEggOpenAnimate');
                        //     eggindex = 0;
                        // }
                        // if (that.attr('data-egg') == 'middle') {
                        //     that.addClass('eggMiddleClicked');
                        //     $('.lottery-text').addClass('showEggOpenAnimate');
                        //     $('.egg-broken-wrap').addClass('eggMiddle showEggOpenAnimate');
                        //     $('.hammer').addClass('hammer-middle');
                        //     $('.light').addClass('light-eggMiddle showEggOpenAnimate');
                        //     eggindex = 1;
                        // }
                        // if (that.attr('data-egg') == 'right') {
                        //     that.addClass('eggRightClicked');
                        //     $('.lottery-text').addClass('showEggOpenAnimate');
                        //     $('.egg-broken-wrap').addClass('eggRight showEggOpenAnimate');
                        //     $('.hammer').addClass('hammer-right');
                        //     $('.light').addClass('light-eggRight showEggOpenAnimate');
                        //     eggindex = 2;
                        // }

                        EggVo.animation(that)



                        lotterySucess = true;

                        var self = this;
                        $('.dialog-result').addClass('showEggOpenAnimate');
                        setTimeout(function () {
                            $(self).addClass('stopShake');
                        }, 3500)

                        LotteryVo.getLotteryCount();

                        var msg = ""

                        if (common["prize"][data.content.awardsCode].status == "1") {
                            msg = "恭喜您获得<b>" + common["prize"][data.content.awardsCode]["title"] + "</b>!<br/>请填写收货地址，公司将在2周内配送，请确保信息正确并保持电话畅通，谢谢！";
                        } else if (common["prize"][data.content.awardsCode].status == "2") {
                            msg = "恭喜您获得<b>" + common["prize"][data.content.awardsCode]["title"] + "</b>!<br/>公司将在2周内电话与您联系领奖事宜，请保持电话畅通，谢谢！";
                        } else if (common["prize"][data.content.awardsCode].status == "0") {
                            msg = "恭喜您获得<b>" + common["prize"][data.content.awardsCode]["title"] + "</b>!<br/>公司将在2周内发放，后期可登录纷享荟“我的”进行查询，谢谢！";
                        } else if (common["prize"][data.content.awardsCode].status == "4") {
                            msg = "很遗憾未中奖，感谢您的参与！"
                        }

                        if (data.content.awardsCode === "8080") {
                            msg = "很遗憾未中奖，感谢您的参与！"
                        }

                        setTimeout(function () {

                            LotteryVo.handleLotteryPrizes(msg,data)

                            // window.canDraw = true;
                            // lotterySucess = false
                            $(".drawNotice  .button,.drawNotice .addressModal").on("click", function () {
                                window.canDraw = true;
                                lotterySucess = false
                                console.log(data,'???code0')
                                EggVo && EggVo.init()
                               // window.location.reload();
                            })
                            // 重置 flag 控制多次点击 和动画
                            layerVo.end()
                            // layer.open({
                            //     title: '温馨提示',
                            //     className: 'drawNotice',
                            //     // content: '<div class="zjnotice">' + msg + '</div><div class="button">' + (common["prize"][data.content.awardsCode].status == "1" ? '<a class="addressModal" style="color: inherit;display:inline;margin-left:10px"' + 'data-quali="' + localStorage.getItem("qualiSeqNo") + '"' + 'class="addressModal" href="javascript:void(0);' + '">' + '点此填写收货地址</a>':'关闭') + '</div>',
                            //     content: '<div class="zjnotice">' + msg + '</div>' + (common["prize"][data.content.awardsCode].status == "1" ? '<div class="address_modal"><a class="addressModal" style="color: inherit;display:inline;margin-left:10px"' + 'data-quali="' + localStorage.getItem("qualiSeqNo") + '"' + 'class="addressModal" href="javascript:void(0);' + '">' + '点此填写收货地址</a>' + '</div>' : '<div class="button">' +'关闭' + '</div>'),
                            //     style: 'width:6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;font-size:18px',
                            //     shadeClose: false,
                            //     end: function () {

                            //     }
                            // });
                            // $(".drawNotice  .button").on("click", function () {
                            //     layer.closeAll();
                            //     getLotteryCount();
                            // })
                        }, 6000)
                    }else if(data) {
                        var code = data.code
                        if(code === 40003) {

                            EggVo.animation(that)


                            lotterySucess = true;

                            var self = this;

                            $('.dialog-result').addClass('showEggOpenAnimate');

                            setTimeout(function () {
                                $(self).addClass('stopShake');
                            }, 3500)

                            // window.canDraw = true;
                            setTimeout(function() {
                                LotteryCodeMap[code] && LotteryCodeMap[code]()
                                // 重置 flag 控制多次点击 和动画
                                lotterySucess = false
                                layerVo.end()
                                console.log(code,'???code1')
                                EggVo && EggVo.init()
                               // window.location.reload(); 
                                // $(".startNotice").on("click",'.button', function () {
                                //     EggVo && EggVo.init()
                                // })

                            },6000);

                            
                        }else {
                            
                            LotteryCodeMap[code] && LotteryCodeMap[code]()
                            lotterySucess = false
                            // 重置 flag 控制多次点击 和动画
                            layerVo.end()
                        }
                        
                        
                    }

                    // if (data && data.code === 40005 || data && data.code === 40006) {
                    //     layer.open({
                    //         type: 3,
                    //         title: '温馨提示',
                    //         className: 'againNotice',
                    //         content: '<div class="notice">' + (data.code === 40005 ?
                    //                 '抽奖活动尚未开始，敬请期待！' : '抽奖活动已结束，感谢关注！') +
                    //             '</div><div class="button">确定</div>',
                    //         style: 'width:6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;font-size:18px',
                    //         shadeClose: false,
                    //         end: function () {
                    //             click = false;
                    //         }
                    //     });
                    //     $(".againNotice  .button").on("click", function () {
                    //         layer.closeAll();
                    //         getLotteryCount();
                    //     })
                    // }
                    // if (data && data.code == 40002) {
                    //     layer.open({
                    //         type: 3,
                    //         title: '温馨提示',
                    //         className: 'errortNotice',
                    //         content: '<div class="notice">卡号未登录，请稍后再试！</div><div class="button">确定</div>',
                    //         style: 'width:6rem; background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;font-size:18px',
                    //         shadeClose: false,
                    //     });
                    //     $(".errortNotice  .button").on("click", function () {
                    //         location.reload();
                    //     })
                    // } else if (data && data.code == 40007) { //超过次数
                    //     layer.open({
                    //         type: 3,
                    //         title: [
                    //             '温馨提示',
                    //             'background-color:transparent; color:black; text-align:center;'
                    //         ],
                    //         className: 'startNotice',
                    //         content: '<div class="zjnotice">' + '您抽奖已超过指定次数' +
                    //             '</div><div class="button">' + (
                    //                 '<a style="text-decoration: none; color: #ff8800;" href="javascript:void(0);" id="checkHistory">查看中奖记录</a>'
                    //             ) + '</div>',
                    //         style: 'width:6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;font-size:18px',
                    //         shadeClose: false,
                    //         end: function () {
                    //             // location.href = common.skipUrl;
                    //         }
                    //     });
                    //     $(".startNotice  .button").on("click", function () {
                    //         layer.closeAll();
                    //         getLotteryCount();
                    //     })

                    //     $(".startNotice #checkHistory").on("click", function () {
                    //         $('.btn').click();
                    //     })

                    // } else if (data && data.code == 40008) { //没有抽奖资格
                    //     layer.open({
                    //         type: 3,
                    //         title: [
                    //             '温馨提示',
                    //             'background-color:transparent; color:black; text-align:center;'
                    //         ],
                    //         className: 'startNotice',
                    //         content: '<div class="zjnotice">你已没有抽奖资格</div><div class="button">关闭</div>',
                    //         style: 'width:6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;font-size:18px',
                    //         shadeClose: false,
                    //         end: function () {
                    //             // location.href = common.skipUrl;
                    //         }
                    //     });
                    //     $(".startNotice  .button").on("click", function () {
                    //         layer.closeAll();
                    //         getLotteryCount();
                    //     })
                    // }  else if (data && data.code == 40003) { //未中奖

                    //     if (that.attr('data-egg') == 'left') {
                    //         that.addClass('eggLeftClicked');
                    //         $('.lottery-text').addClass('showEggOpenAnimate');
                    //         $('.egg-broken-wrap').addClass('eggLeft showEggOpenAnimate');
                    //         $('.hammer').addClass('hammer-left');
                    //         $('.light').addClass('light-eggLeft showEggOpenAnimate');
                    //         eggindex = 0;
                    //     }
                    //     if (that.attr('data-egg') == 'middle') {
                    //         that.addClass('eggMiddleClicked');
                    //         $('.lottery-text').addClass('showEggOpenAnimate');
                    //         $('.egg-broken-wrap').addClass('eggMiddle showEggOpenAnimate');
                    //         $('.hammer').addClass('hammer-middle');
                    //         $('.light').addClass('light-eggMiddle showEggOpenAnimate');
                    //         eggindex = 1;
                    //     }
                    //     if (that.attr('data-egg') == 'right') {
                    //         that.addClass('eggRightClicked');
                    //         $('.lottery-text').addClass('showEggOpenAnimate');
                    //         $('.egg-broken-wrap').addClass('eggRight showEggOpenAnimate');
                    //         $('.hammer').addClass('hammer-right');
                    //         $('.light').addClass('light-eggRight showEggOpenAnimate');
                    //         eggindex = 2;
                    //     }

                    //     window.canDraw = true;

                    //     lotterySucess = true;

                    //     var self = this;

                    //     $('.dialog-result').addClass('showEggOpenAnimate');

                    //     setTimeout(function () {
                    //         $(self).addClass('stopShake');
                    //     }, 3500)

                    //     window.canDraw = true;

                    //     setTimeout(function() {
                    //         layer.open({
                    //             type: 3,
                    //             title: [
                    //                 '温馨提示',
                    //                 'background-color:transparent; color:black; text-align:center;'
                    //             ],
                    //             className: 'startNotice',
                    //             content: '<div class="zjnotice">未中奖</div><div class="button">关闭</div>',
                    //             style: 'width:6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;',
                    //             shadeClose: false,
                    //             end: function () {
                                    
                    //             }
                    //         });
                    //         $(".startNotice  .button").on("click", function () {
                    //             layer.closeAll();
                    //             getLotteryCount();
                    //         })
                    //     },6000);


                    // }

                },
            });
        }
    }

    function login(type) {
        layer.open({
            type: 3,
            title: [
                '登录您的账号',
                'background-color:transparent; color:black; text-align:center;font-size:22px'
            ],
            className: 'login-popuo',
            content: '<div class="pwd"><input class="staffNum" name="staffNum" type="tel" placeholder="请输入您的卡号" /></div><div class="pwd"><input class="password" name="password" type="password" placeholder="请输入您的密码" /></div><p class="error"></p><div class="button" data-type=' + type + '>登录</div>',
            style: 'width:6rem; min-height:6rem; background-color:#fff; color:black; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;font-size:18px',
            shadeClose: false
        });

    }

    function loading(isOpen) {
        $('.loading-bar')[isOpen ? 'removeClass' : 'addClass']('hidden');
    }

    // 登录监听
    // mai 登录接口
    $('#container').on("click", ".login-popuo .button", function (e) {
        var current = $(e.currentTarget);
        var container = current.closest('.login-popuo');
        var inputVal1 = trim(container.find(".staffNum").val()),
            inputVal2 = trim(container.find(".password").val());
        var type = current.attr('data-type');
        var t = +new Date();

        if (JSON.parse(localStorage.getItem("isLogin")) && JSON.parse(localStorage.getItem("isLogin")).login !== 0) {
            return;
        }

        if (window.isLogined) {
            return;
        }

        if (!type) {
            setTimeout(function() {
                layer.closeAll();
            },300)
            return;
        }

        if (inputVal1 != "" && inputVal2 != "") {
            $.ajax({
                type: "post",
                url: common.url + "/sys/login",

                dataType: "json",
                data: {
                    dealerNo: inputVal1,
                    password: hex_md5(inputVal2)
                },
                beforeSend: function () {
                    loading(1);
                    window.isLogined = true;
                },
                complete: function () {
                    loading();
                },
                success: function (data) {
                    /* 
                        40005 活动未开始 不可登录
                        40006 活动已结束 可登陆
                    */
                    if (data && data.code === 40006) {
                        common.staffNum = inputVal1;
                        localStorage.setItem("isLogin", JSON.stringify({
                            login: 1,
                            staffNum: common.staffNum
                        })); //保存登录信息
                    }
                    if (type == 2) {
                        // location.href = './history.html';
                        return;
                    }

                    

                    if(data) {
                        var code = data.code
                        LotteryCodeMap[code] && LotteryCodeMap[code]()
                    }

                    // if (data && data.code === 40005 || data && data.code === 40006) {
                    //     layer.open({
                    //         type: 3,
                    //         title: '温馨提示',
                    //         className: 'againNotice',
                    //         content: '<div class="notice">' + (data.code === 40005 ?
                    //                 '抽奖活动尚未开始，敬请期待！' : '抽奖活动已结束，感谢关注！') +
                    //             '</div><div class="button">确定</div>',
                    //         style: 'width:6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;font-size:18px',
                    //         shadeClose: false,
                    //         end: function () {
                    //             click = false;
                    //         }
                    //     });
                    //     $(".againNotice  .button").on("click", function () {
                    //         layer.closeAll();
                    //         getLotteryCount();
                    //     })
                    // }

                    common.staffNum = inputVal1;
                    localStorage.setItem("isLogin", JSON.stringify({
                        login: 1,
                        staffNum: common.staffNum
                    })); //保存登录信息

                    localStorage.setItem("deploycolId", common.deploycolId);

                    if (type == 1) { // 点击抽奖登录 成功后直接抽奖
                        // startDraw();
                    } else { // 点击 中奖纪录登录  成功后跳转
                        // location.href = './history.html';
                    }

                },
                error: function (data) {
                    if (data.status == 400) {
                        // 1为点击抽奖时  登录   2为点击查看历史登录
                        if (type == 1 && data.responseText == '您已抽过奖') {
                            LotteryVo.handleOverLottery();
                            // layer.open({
                            //     type: 3,
                            //     title: [
                            //         '温馨提示',
                            //         // 'background-color:#58a0ea; color:#fff; text-align:center;'
                            //         'background-color: transparent; color:black; text-align:center;'
                            //     ],
                            //     className: 'againNotice',
                            //     content: '<div class="zjnotice">您已经抽过奖了，不能重复抽奖，谢谢！</div><div class="button">确定</div>',
                            //     style: 'width:6rem;background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;font-size:18px',
                            //     shadeClose: false,
                            //     end: function () {
                            //         // location.href = common.skipUrl;
                            //     }
                            // });
                        } else {
                            console.log(data);
                            container.find('.error').addClass('red').text('*卡号或密码不正确，请重新输入');
                        }
                        $(".againNotice  .button").on("click", function () {
                            layer.closeAll();
                            LotteryVo.getLotteryCount();
                        })
                        window.isLogined = false;
                    } 
                    else if (data.status == 200) {
                        layer.closeAll();
                        common.staffNum = inputVal1;
                        localStorage.setItem("isLogin", JSON.stringify({
                            login: 1,
                            staffNum: common.staffNum
                        })); //保存登录信息
                        localStorage.setItem("deploycolId", common.deploycolId);
                        LotteryVo.getLotteryCount();
                        window.canDraw = true;
                        if (type == 1) { // 点击抽奖登录 成功后直接抽奖
                            // startDraw();
                        } else { // 点击 中奖纪录登录  成功后跳转
                            // location.href = './history.html';
                        }
                        window.isLogined = true;
                    } 
                    else {
                        layer.open({
                            type: 3,
                            title: '温馨提示',
                            className: 'errortNotice',
                            content: '<div class="notice">' + common.notice1 +
                                '</div><div class="button">确定</div>',
                            style: 'width:6rem; background-color:#fff; border:none;border-radius:6px;box-shadow: 0px 0px 15px #000000;font-size:18px',
                            shadeClose: false,
                        });
                        $(".errortNotice  .button").on("click", function () {
                            location.reload();
                        })
                    }
                    window.isLogined = false;
                }
            })

        } else {
            container.find('.error').addClass('red').text('*' + (!inputVal1 ? '卡号' : '密码') + '不能为空');
        }
    })

    function trim(str) { //删除左右两端的空格
        return str.replace(/(^\s*)|(\s*$)/g, "");
    }

})